import * as React from 'react';

import Component from './Component';
import Loading from './Loading';

export interface ILoadingProps {
    showLoading?: boolean;
    message?: string;
}
export interface ILoadingState {
}

export default class LoadingComponent<LoadingProps, LoadingState> extends Component<any, any> {
    constructor(props: LoadingProps) {
        super(props);
        this.state = Object.assign({
            showLoading: this.props.showLoading === undefined ? true : this.props.showLoading,
            componentLoad: false,
            fetchLoad: false,
        }, this.state);
    }
    // 组件将要加载
    componentWillMount() {
        // console.log('LoadingComponent.componentWillMount');
        this.fetchLoad();
    }
    // 组件已经加载
    componentDidMount() {
        // console.log('LoadingComponent.componentDidMount');
        this.componentLoad();
    }

    componentWillUnmount?(): void;
    componentWillReceiveProps?(nextProps: any, nextContext: any): void;
    shouldComponentUpdate?(nextProps: any, nextState: any, nextContext: any): boolean;
    componentWillUpdate?(nextProps: any, nextState: any, nextContext: any): void;
    componentDidUpdate?(prevProps: any, prevState: any, prevContext: any): void;

    componentLoad = (data: any = {}) => {
        data.componentLoad = true;
        this.setState(data);
    }

    fetchLoad = (data: any = {}) => {
        data.fetchLoad = true;
        this.setState(data);
    }

    renderUI() {
        // override by child class 
        return null;
    }

    renderLoading() {
        return <Loading message={this.props.message} />;
    }

    /*** auto call renderUI*/
    renderIf(): JSX.Element {
        let {componentLoad, fetchLoad, showLoading} = this.state;
        // console.log([componentLoad, fetchLoad, showLoading])
        return (
            showLoading === false || componentLoad && fetchLoad ? this.renderUI() : this.renderLoading()
        );
    }

    /*** auto call renderUI*/
    render() {
        return this.renderIf();
    }
}
